package at.bherbst;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.util.Log;

public class UDPSenderRunnable implements Runnable {

	private static final String TAG = "UDPSenderRunnable";
	private int server_port = 1500;
	private InetAddress local;
	private DatagramSocket s;
	private UDPData data;

	UDPSenderRunnable(UDPData data, String ip) {
		this.data = data;
		try {
			this.local = InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			int lastSentCount = 0;
			s = new DatagramSocket();
			Log.d(TAG, "starting loop");
			while (!Thread.interrupted()) {
				if (data.count > lastSentCount && data.value != 0) {
					String message = data.value+"";
					int msg_length = message.length();
					byte[] message2 = message.getBytes();
					DatagramPacket p = new DatagramPacket(message2, msg_length,
							local, server_port);
					s.send(p);
					lastSentCount = data.count;
				}
				Log.d(TAG,"waiting for Lock");
				data.lock.lock();
				Log.d(TAG,"Lock released");
				data.lock.unlock();
				Log.d(TAG,"Lock acquired");
			}
			Log.d(TAG, "loop left");
		} catch (Exception e) {
			e.printStackTrace();
			s.close();
		}
	}

}
